# coding:utf-8

import simplejson as simplejson
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponseNotFound
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView

from djcelery import models as celery_models

from .forms import *
from django.views.generic.base import TemplateView


@login_required
def homePage(request):
    if request.method == 'POST':
        return
    elif request.user.is_authenticated:
        return HttpResponseRedirect('/task_results/')
    else:
        return HttpResponseRedirect('/login/')



@login_required
def settings_del(request, id):
    f = get_object_or_404(AppSettings, pk=int(id))
    f.delete()
    return HttpResponseRedirect('/settings/')


@login_required
def plugins(request):
    ''' 扫描插件返回插件列表
    '''
    from main.functions.load_plugins import get_all_plugins
    got_plugins = get_all_plugins()

    context = {'object_list': got_plugins, 'posturl': 'home', 'editurl': 'home'}
    return render(request, 'public/plugins.html', context)


@login_required
def settings_edit(request, id):
    if id:
        f = get_object_or_404(AppSettings, pk=int(id))
        form = AppSettingsForm(instance=f)
        context = {'posturl': 'settings', 'form': form, 'title': '修改设置'}
        return render(request, 'edit_base.html', context)
    else:
        context = {'posturl': 'settings', 'form': AppSettingsForm(), 'title': '新增设置'}
        return render(request, 'edit_base.html', context)


@login_required
def settings(request):
    if request.method == 'POST':
        id = request.POST.get('id')
        form = AppSettingsForm(request.POST, instance=get_object_or_404(AppSettings, pk=int(id)) if id else None)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/settings/')

    context = {'item_list': AppSettings.objects.all(), 'form': AppSettingsForm(), 'posturl': 'settings',
               'editurl': 'settings_edit'}
    return render(request, 'public/settings.html', context)


@login_required
def djcelery_interval_schedule_del(request, id):
    f = get_object_or_404(celery_models.IntervalSchedule, pk=int(id))
    f.delete()
    return HttpResponseRedirect('/djcelery_interval_schedule/')


@login_required
def djcelery_interval_schedule_edit(request, id):
    if id:
        f = get_object_or_404(celery_models.IntervalSchedule, pk=int(id))
        form = djcelery_intervalschedule_form(instance=f)
        context = {'posturl': 'djcelery_interval_schedule', 'form': form, 'title': '编辑周期执行计划'}
        return render(request, 'edit_base.html', context)
    else:
        context = {'posturl': 'djcelery_interval_schedule', 'form': djcelery_intervalschedule_form(),
                   'title': '新增周期执行计划'}
        return render(request, 'edit_base.html', context)


@login_required
def djcelery_interval_schedule(request):
    if request.method == 'POST':
        id = request.POST.get('id')
        form = djcelery_intervalschedule_form(request.POST, instance=get_object_or_404(celery_models.IntervalSchedule,
                                                                                       pk=int(id)) if id else None)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/djcelery_interval_schedule/')
    else:
        context = {'item_list': celery_models.IntervalSchedule.objects.all(), 'form': djcelery_intervalschedule_form(),
                   'posturl': 'djcelery_interval_schedule', 'editurl': 'djcelery_interval_schedule_edit'}
        return render(request, 'public/djcelery_interval_schedule.html', context)


@login_required
def djcelery_crontab_schedule_del(request, id):
    f = get_object_or_404(celery_models.CrontabSchedule, pk=int(id))
    f.delete()
    return HttpResponseRedirect('/djcelery_crontab_schedule/')


@login_required
def djcelery_crontab_schedule_edit(request, id):
    if id:
        f = get_object_or_404(celery_models.CrontabSchedule, pk=int(id))
        form = djcelery_crontabschedule_form(instance=f)
        context = {'posturl': 'djcelery_crontab_schedule', 'form': form, 'title': '编辑定期执行计划'}
        return render(request, 'edit_base.html', context)
    else:
        context = {'posturl': 'djcelery_crontab_schedule', 'form': djcelery_crontabschedule_form(), 'title': '新增定期执行计划'}
        return render(request, 'edit_base.html', context)


@login_required
def djcelery_crontab_schedule(request):
    if request.method == 'POST':
        id = request.POST.get('id')
        form = djcelery_crontabschedule_form(request.POST, instance=get_object_or_404(celery_models.CrontabSchedule,
                                                                                      pk=int(id)) if id else None)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/djcelery_crontab_schedule/')
    else:
        context = {'item_list': celery_models.CrontabSchedule.objects.all(), 'form': djcelery_crontabschedule_form(),
                   'posturl': 'djcelery_crontab_schedule', 'editurl': 'djcelery_crontab_schedule_edit'}
        return render(request, 'public/djcelery_crontab_schedule.html', context)


@login_required
def djcelery_periodictask_del(request, id):
    get_object_or_404(celery_models.PeriodicTask, pk=int(id)).delete()
    return HttpResponseRedirect('/djcelery_periodictask/')


@login_required
def djcelery_periodictask_edit(request, id):
    if id:
        f = get_object_or_404(celery_models.PeriodicTask, pk=int(id))
        form = djcelery_periodictask_form(instance=f)
        print(f)
        context = {'posturl': 'djcelery_periodictask', 'form': form, 'title': '编辑任务'}
        return render(request, 'edit_base.html', context)
    else:
        context = {'posturl': 'djcelery_periodictask', 'form': djcelery_periodictask_form(), 'title': '新增任务'}
        return render(request, 'edit_base.html', context)


@login_required
def djcelery_periodictask(request):
    if request.method == 'POST':
        id = request.POST.get('id')
        form = djcelery_periodictask_form(request.POST, instance=get_object_or_404(celery_models.PeriodicTask,
                                                                                      pk=int(id)) if id else None)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/djcelery_periodictask/')
        else:
            return HttpResponseNotFound('<h1>form is not valid</h1>')
    else:
        context = {'item_list': celery_models.PeriodicTask.objects.all(), 'form': djcelery_periodictask_form(),
                   'posturl': 'djcelery_periodictask', 'editurl': 'djcelery_periodictask_edit'}
        return render(request, 'public/djcelery_periodictask.html', context)

class task_results(TemplateView):

    template_name = 'public/taskresult_list.html'

    def get_context_data(self, **kwargs):
        context = super(task_results, self).get_context_data(**kwargs)
        context['object_list'] = TaskResults.objects.all()
        context['form'] = TaskResultsForm()
        context['porturl'] = 'task_results'
        context['editurl'] = 'task_results'

        return context

@login_required
def task_result_detail(request, id):
    if id:
        f = get_object_or_404(TaskResults, pk=int(id))
        form = TaskResultsForm(instance=f)
        context = {'form': form, 'title': '任务状态 - 详情'}
        return render(request, 'detail_base.html', context)